package com.yqg.protection.controller;

import com.alibaba.fastjson.JSON;
import com.yqg.protection.common.Result;
import com.yqg.protection.common.result.ResultCodeEnum;
import com.yqg.protection.entity.InspectAddrCode;
import com.yqg.protection.exception.ServiceException;
import com.yqg.protection.mapper.InspectAddrCodeMapper;
import com.yqg.protection.utils.QRCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/qrCode")
public class QRCodeGeneratorController {

    @Autowired
    InspectAddrCodeMapper inspectAddrCodeMapper;

   @Value("${files.upload.path}")
    private String fileUploadPath;
    private static final String FileFormat=".png";

    private static final ThreadLocal<SimpleDateFormat> LOCALDATEFORMAT=ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyyMMddHHmmss"));
   @GetMapping("/generator")
   public Result encodeQrCode(String content,Long id) {
       InspectAddrCode inspectAddrCode = inspectAddrCodeMapper.selectById(id);
       try {
            final String fileName=LOCALDATEFORMAT.get().format(new Date());
            String codeToFile = QRCodeUtil.createCodeToFile(content, new File(fileUploadPath), fileName + FileFormat, id.toString());
            inspectAddrCode.setAddrCode(codeToFile);
            inspectAddrCodeMapper.updateById(inspectAddrCode);
        }catch (Exception e){
            throw new ServiceException(JSON.toJSONString(ResultCodeEnum.FAIL),e.getMessage());
        }
        return Result.success("二维码生成成功");
   }
}
